<template>
    <div>
        <!-- 反担保资料上传:rzFdbzlsc -->
        <div class="w_100 headTips d_f j_c_s_b">
            <div class="d_f a_i_c">
                <div class="line"></div>
                {{ name }}
            </div>
            <div class="isClose" @click="close">
                <el-icon v-if="type == 'smallForm'">
                    <CloseBold />
                </el-icon>
            </div>
            <el-switch v-if="type == 'bigForm'" @change="change" v-model="status"
                style="--el-switch-on-color: #13ce66;" />
            <el-button type="primary" v-if="type == 'useForm' && isReset == 1" @click="clearForm">清除表单</el-button>
        </div>
        <div class="formBox rzFdbzlsc">
            <el-upload class="upload-demo" :action="action" :headers="headers" :show-file-list="false"
                :before-upload="beforeUpload" :on-success="onSuccess" multiple :limit="100000000">
                <el-button :icon="Upload" :disabled="type == 'useForm' && !isAudit ? false : true"
                    type="primary">上传资料</el-button>
            </el-upload>

            <mytable :fields="fields" width="150" ref="tableRef"
                :defaultList="model.counterGuarantee.counterGuaranteeUpload" class="m_t_16" :isSelection="false"
                :isPaginationShow="false">
                <template v-slot:operation="{ row, $index }">
                    <div class="d_f j_c_s_b">
                        <span class="success" @click="preview(row)">预览</span>
                        <el-upload class="upload-demo" :action="action" :headers="headers" :show-file-list="false"
                            :before-upload="beforeUpload" :on-success="onSuccess1" multiple :limit="100000000">
                            <span class="edit" @click="reUpload($index)" v-if="!isAudit">重新上传</span>
                        </el-upload>
                        <span class="error" @click="deleteOut($index)" v-if="!isAudit">删除</span>
                    </div>
                </template>
            </mytable>
            <div class="rzFdbzlsc_form1">
                <myform :fields="fields1" :model="model.counterGuarantee" :rules="rules" ref="form" class="m_t_16">
                    <template v-slot:counterGuarantee>
                        <el-radio-group :disabled="isAudit" v-model="model.counterGuarantee.counterGuarantee">
                            <el-radio :value="2">是</el-radio>
                            <el-radio :value="3">否</el-radio>
                        </el-radio-group>
                        <!-- <span class="size">若选择“是”，则将进入预警流程</span> -->
                    </template>
                </myform>
            </div>
            <div class="segment" v-if="fields2.length > 0"></div>
            <div class="formArrow d_f a_i_c m_t_30" v-if="fields2.length > 0">
                <img src="../../assets/formArrow.png" alt="">
                <span>{{ subTitle || '新加字段' }}</span>
            </div>
            <div class="acceptance_form" v-if="fields2.length > 0">
                <myform :fields="fields2" :model="model.counterGuarantee" :options="options" class="m_t_16">
                </myform>
            </div>
        </div>
    </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, onBeforeMount, ref } from 'vue'
import { rzFdbzlscType } from './data'
import { CloseBold, Upload } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { formGet, unitFormSet } from '../../api/system/flowPath'
import { listByParentArr } from '../../api/login'
import { ElMessageBox } from 'element-plus'
import { httpConfig } from '../../utils/config'
import { Message } from '../../utils/resetMessage'
import { copy, fileFormat, momentNewDate } from '../../utils/date'
const model = {
    counterGuarantee: {
        counterGuaranteeUpload: [],
        counterGuarantee: 2,
        counterGuaranteeRemark: '',
    },
    guaranteeDeleteData: [],
}
export default defineComponent({
    name: '',
    props: {
        type: {
            type: String,
            default: '',
        },
        unitId: {
            type: [String, Number],
            default: '',
        },
        isEnabled: {
            type: Number,
            default: '',
        },
        nodeObj: {
            type: Object,
            default: {}
        },
        vars: {
            type: Object,
            default: {}

        },
        isAudit: {
            type: Boolean,
            default: true
        }
    },
    components: {
        CloseBold
    },
    setup(props: any) {
        const data: rzFdbzlscType = reactive({
            name: '反担保资料上传',
            status: true,
            options: {},
            model: copy(model),
            subTitle: '',
            fields: [
                {
                    label: '资料名称',
                    prop: 'businessDataName',
                },
                {
                    label: '上传环节',
                    prop: 'nodeName',
                },
                {
                    label: '上传人',
                    prop: 'uploadName',
                },
                {
                    label: '上传时间',
                    prop: 'uploadTime',
                },
            ],
            fields1: [
                {
                    label: '反担保措施是否已落实',
                    prop: 'counterGuarantee',
                    labelWidth: '200px',
                    disabled: false,
                },
                {
                    label: '备注',
                    prop: 'counterGuaranteeRemark',
                    type: "textarea",
                    labelWidth: '200px',
                    placeholder: '有无其他抵（质）押措施，若有需说明',
                    disabled: false,
                },
            ],
            rules: {
                counterGuarantee: [
                    { required: true, message: '请选择反担保措施', trigger: 'change' },
                ],
                // counterGuaranteeRemark: [
                //     { required: true, message: '请输入备注', trigger: 'blur' },
                // ],
            },
            fields2: [],
            action: httpConfig.upload,
            headers: {
                token: localStorage.getItem('Token')
            },
            index: 0,
            id: '',
            isReset: 2,
        })
        const form = ref()
        const router = useRouter()
        onBeforeMount(() => {
            methods.getData()
            data.status = props.isEnabled == 0 ? false : true
        })
        const methods = {
            close() {
                router.push('/system/flowPath/childForm/index')
            },
            //文件上传之前校验格式
            beforeUpload(file: any) {
                return fileFormat(file, ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'png', 'jpg', 'jpeg', 'JPG', 'zip', 'txt', 'pptx', 'gif', 'rar', 'ppt','PNG','JPEG'], '')
            },
            //获取自定义表单
            getData() {
                formGet({ tag: 'rzFdbzlsc' }).then((res: any) => {
                    data.name = res.name
                    data.id = res.id
                    data.isReset = res.isReset
                    if (!res.formStruct || res.formStruct == 'null' || res.formStruct == '{}') return
                    data.subTitle = res.subTitle
                    let formStruct = JSON.parse(res.formStruct)
                    formStruct.formFields.map((item: any) => {
                        data.model.counterGuarantee[item.prop] = ''
                    })
                    data.fields2 = formStruct.formFields

                    data.fields1.map((item: any) => {
                        item.disabled = props.isAudit
                    })
                    data.fields2.map((item: any) => {
                        item.disabled = props.isAudit
                    })
                    if (props.vars) {
                        const localData = props.vars
                        for (let key in data.model.counterGuarantee) {
                            if (localData.counterGuarantee[key] != null) {
                                data.model.counterGuarantee[key] = localData.counterGuarantee[key]
                            }
                        }
                        data.model.counterGuarantee.counterGuaranteeUpload = localData.counterGuarantee.counterGuaranteeUpload || []
                        if (props.type == 'useForm') {
                            data.model.counterGuarantee.counterGuaranteeRemark = ''
                        }
                    }

                    let arr = formStruct.formFields.filter((item: any) => {
                        return item.type == 'select'
                    })
                    let ids = arr.map((item: any) => {
                        return item.prop
                    })
                    if (ids.length == 0) return
                    listByParentArr({ ids: ids }).then((res: any) => {
                        ids.map((item: any) => {
                            data.options[item] = res[item]
                        })
                    })
                })
            },
            //上传文件
            onSuccess(e: any, file: any) {
                if (e.code == '000000') {
                    let obj: any = {
                        fileUrl: e.data,
                        uploadName: JSON.parse(<string>localStorage.getItem('userVO')).name,
                        uploadTime: momentNewDate(),
                        businessDataName: file.name,
                        nodeName: props.nodeObj.name,
                        nodeId: props.nodeObj.id,
                    }
                    data.model.counterGuarantee.counterGuaranteeUpload.push(obj)
                } else {
                    Message({ type: 'error', message: e.msg })
                }
            },
            onSuccess1(e: any, file: any) {
                if (e.code == '000000') {
                    if (data.model.counterGuarantee.counterGuaranteeUpload[data.index].nodeId) {
                        data.model.guaranteeDeleteData.push({ delNodeId: data.model.counterGuarantee.counterGuaranteeUpload[data.index].nodeId })
                    }
                    data.model.counterGuarantee.counterGuaranteeUpload[data.index].fileUrl = e.data,
                        data.model.counterGuarantee.counterGuaranteeUpload[data.index].businessDataName = file.name
                    data.model.counterGuarantee.counterGuaranteeUpload[data.index].uploadName = JSON.parse(<string>localStorage.getItem('userVO')).name
                    data.model.counterGuarantee.counterGuaranteeUpload[data.index].uploadTime = momentNewDate()
                    data.model.counterGuarantee.counterGuaranteeUpload[data.index].nodeName = props.nodeObj.name
                    data.model.counterGuarantee.counterGuaranteeUpload[data.index].nodeId = props.nodeObj.id
                } else {
                    Message({ type: 'error', message: e.msg })
                }
            },
            //预览文件
            preview(row: any) {
                window.open(row.fileUrl, '_blank')
            },
            //重新上传
            reUpload(index: number) {
                data.index = index
            },
            //删除文件
            deleteOut(index: number) {
                ElMessageBox.confirm(
                    '是否删除当前文件?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'error',
                    }
                )
                    .then(() => {
                        if (data.model.counterGuarantee.counterGuaranteeUpload[index].nodeId) {
                            data.model.guaranteeDeleteData.push({ delNodeId: data.model.counterGuarantee.counterGuaranteeUpload[index].nodeId })
                        }

                        data.model.counterGuarantee.counterGuaranteeUpload.splice(index, 1)
                    })
            },
            //设置表单的启用跟停用
            change() {
                unitFormSet({ isEnabled: data.status ? 1 : 0, id: data.id, unitId: props.unitId }).then(() => {
                    Message({ type: 'success', message: '设置成功' })
                }).catch(() => {
                    data.status = !data.status
                })
            },
            //清除表单数据
            clearForm() {
                data.model = copy(model)
            },
            resultData() {
                return new Promise((resolve, reject) => {
                    form.value.verification().then(() => {
                        resolve(data.model)
                    })
                })
            },
            saveData() {
                return new Promise((resolve, reject) => {
                    resolve(data.model)
                })
            },
        }

        return {
            ...toRefs(data),
            form, ...methods, Upload
        }
    }
})
</script>
<style lang='scss'>
.rzFdbzlsc {
    .el-form-item {
        width: 50% !important;
        margin-right: 0px !important;

        .el-form-item__content {
            width: calc(100% - 200px) !important;

            .el-input,
            .el-cascader,
            .el-select {
                width: 100% !important;
            }
        }
    }
}

.rzFdbzlsc_form1 {
    .el-form-item {
        width: 100% !important;
    }

    // .size {
    //     color: rgba(0, 0, 0, 0.4);
    //     font-size: 11px;
    //     margin-left: 20px;
    // }
}
</style>